<template>
  <div class="box-container">
    <el-card style="max-width: 1000px;margin:10px 0;height: 30px;padding-left: 20px">
      我的消息
    </el-card>

    <el-card style="max-width: 1000px;min-height: 200px;">
      <div class="container">
        <div class="left">
          <div class="left-header">
            近期消息
          </div>
          <div class="left-content" v-infinite-scroll="load" :infinite-scroll-disabled="disabled">
            <div class="chat-list-box">
              <div class="chat-item" :class="currentPointer === index?'chat-active':''" @click="chatWith(index,item.userId,item.nickname)" v-for="(item,index) in chatterList" :key="item.userId">
                <div class="chatter-avatar">
                  <img :src="item.userAvatar" width="40" height="40" :alt="item.nickname">
                </div>
                <div class="chatter-text-box">
                  <div class="chatter-name">
                    {{item.nickname}}
                    <span v-if="item.noReadCount" class="badge">{{item.noReadCount}}</span>
                  </div>
                  <div class="chatter-last-record">
                    {{item.lastMessage.content}}
                  </div>n
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="right-header">
            {{currentChatter.chatterName}}
          </div>
          <el-divider></el-divider>
          <div class="right-content"
               ref="scrollContainer"
               @scroll="handleScroll"
          >
            <div v-if="isLoading">加载中...</div>
            <div class="chat-record-item" v-for="item in currentRecordList" :key="item.id">
              <div class="send-time">
                {{item.ceateTime}}
              </div>
              <template v-if="item.senderId === myId">
                <div class="record-info-mine">
                  <div class="place-rectify">
                    <div class="record-content-mine">
                      <p class="content-text">
                        {{item.content}}
                      </p>
                      <div class="content-img" v-if="item.contentImg">
                        <img :src="item.contentImg" alt="" >
                      </div>
                    </div>
                    <div class="send-avatar-mine">
                      <img :src="item.senderAvatar" alt="" width="30">
                    </div>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="record-info">
                  <div class="send-avatar">
                    <img :src="item.senderAvatar" alt="" width="30">
                  </div>
                  <div class="record-content">
                    <p class="content-text">
                      {{item.content}}
                    </p>
                    <div class="content-img" v-if="item.contentImg">
                      <img :src="item.contentImg" alt="" >
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
          <div class="send-area">
            <div class="send-file">
              <el-icon><Picture /></el-icon>
              <div class="space"></div>
              <el-icon><VideoCamera /></el-icon>
            </div>
            <div class="content-area">
              <el-input
                  v-model="sendContentInfo.content"
                  maxlength="500"
                  :rows="3"
                  show-word-limit
                  type="textarea"
                  @keyup.enter="sendMessage"
              />
            </div>
            <div class="send">
              <el-button @click="sendMessage">发送</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script setup>
/**
 * 这里需要使用WebSocket，目前只是模拟数据，希望以后使用WebSocket时这些能发挥作用。。。
 */
import {nextTick, onMounted, reactive, ref} from "vue";
import {getChatterList, getMsgListByUID, getNoReadMsg, updateNoReadMsg} from "@/api/api.js";
import {useUserStore} from "@/stores/userInfoStore.js";
import emitter from "@/utils/emitter.js";

const updateAndGet = async (userId,isUpdate) => {
  console.log("开始的时候")
  console.log(chatterList.value)
  if(isUpdate){
    const updateRes = await updateNoReadMsg(userId);
  }
  // 获取所有未读的记录
  const noReadRes = await getNoReadMsg();
  console.log(noReadRes.data)
  emitter.emit("updateNoReadCount",noReadRes.data.total)
  //列表中插入记录
  if(noReadRes.data.noReadItems === null || noReadRes.data.noReadItems.length === 0){
    chatterList.value.forEach(ele=>{
      if(ele.noReadCount > 0){
        ele.noReadCount = 0
      }
    })
    return
  }
  console.log(chatterList.value)
  const noReadBox = [] // 这里的循环费了很久的时间和脑力
  noReadRes.data.noReadItems.forEach((item)=>{
    chatterList.value.forEach(ele=>{
      if(ele.userId === item.userId){
        console.log(ele.userId,item.userId)
        console.log(item.count)
        ele.noReadCount = item.count
        noReadBox.push(item.userId)
      }else {
        console.log(noReadBox,ele.userId)
        if(!noReadBox.includes(ele.userId)){
          console.log("设置0")
          ele.noReadCount = 0
        }
      }
    })
  })
  console.log("之后")
  console.log(chatterList.value)
}
let noRead
onMounted(async ()=>{ // 当挂载时
  // 获取所有聊天者列表
  const res = await getChatterList(pageParams.page, pageParams.pageSize)
  console.log(res.data.records)
  chatterList.value = res.data.records
  if(chatterList.value.length === 0){

    return
  }
  // 并初始化第一个聊天者的聊天记录
  myId.value = useUserStore().userInfo.userId // 初始化我的id
  currentChatter.value.id = chatterList.value[0].id
  currentChatter.value.chatterId = chatterList.value[0].userId
  currentChatter.value.chatterName = chatterList.value[0].nickname
  await updateAndGet(chatterList.value[0].userId,true)
  /*
  *               [{}]
                  [{}]
  * */

  // 创建对应的Socket连接
  if('WebSocket' in window){
    websocket = new WebSocket(`ws://localhost:8080/ws/${myId.value}/${currentChatter.value.chatterId}`)
  }else{
    alert("Not support WebSocket")
  }
  initWebSocket(websocket)
  await initLoad()
})

/*左边的聊天者相关*/
// 聊天者列表
const chatterList = ref([])
// 查询参数
const pageParams = {
  page:1,
  pageSize:5,
}

const currentPointer = ref(0) // 当前聊天者指针，css效果
const currentChatter = ref({})  // 当前聊天者,右侧数据
const myId = ref() // 我的id

/* 右边的聊天记录相关*/
// 当前聊天记录
const currentRecordList = ref([])
// 和指定的人聊天
/**
 *
 * @param index
 * @param id  聊天人id
 * @param name  聊天人昵称
 * @returns {Promise<void>}
 */
const chatWith = async (index,id, name) => {
  // 重新初始化参数（很重要！！！）
  hasMore.value = true
  currentPage.value = 1
  currentPointer.value = index // 更新指针，用于css效果
  // 更新聊天者信息
  currentChatter.value.chatterId = id
  currentChatter.value.chatterName = name
  // 获取聊天记录
  const res = await getMsgListByUID(id,currentPage.value++,10);
  console.log(res.data.records)
  currentRecordList.value = res.data.records
  await updateAndGet(id,true)
  // 滚动到最底部
  await nextTick(() => {
    scrollToBottom()
  })
  // 创建对应的Socket连接
  if('WebSocket' in window){
    websocket = new WebSocket(`ws://localhost:8080/ws/${myId.value}/${id}`)
  }else{
    alert("Not support WebSocket")
  }
  initWebSocket(websocket)
}
let websocket = null

/* 发送消息相关 */
const sendContentInfo = reactive({
  senderId:myId.value,
  receiverId:currentChatter.value.chatterId,
  content:''
})
const sendMessage = () => {
  if(websocket === null){
    alert("WebSocket is not open")
  }
  // websocket.send(JSON.stringify(sendContentInfo.content))
  websocket.send(sendContentInfo.content)
  sendContentInfo.content = ''
}
 function initWebSocket(websocket){
  websocket.onerror = function(event){
    console.log("WebSocket error")
  }

  websocket.onopen = function(event){
    console.log("WebSocket open")
  }

  websocket.onmessage = async function(event){
    console.log(event.data)
    const data = JSON.parse(event.data)
    console.log(data)
    const obj = {
      id:currentRecordList.value.length + 1,
      senderId:12,
      receiverId:13,
      content:event.data,
      createTime:"2023-05-17 12:00"
    }
    console.log("当前聊天者id："+currentChatter.value.chatterId)
    if(data.receiverId !== currentChatter.value.chatterId){
      // 重新获取聊天列表
      const res = await getChatterList(1,500);
      chatterList.value = res.data.records
      console.log("在外面")
      console.log(chatterList.value)
      await updateAndGet(data.receiverId,false)
    }else{
      currentRecordList.value.push(data)
    }

    console.log("WebSocket message")
    await nextTick(() => {
      scrollToBottom()
    })
  }

  websocket.onclose = function(event){
    console.log("WebSocket close")
  }
  websocket.onbeforeunload = function(event){
    websocket.close()
  }

}

/* 上拉加载更多数据 */
// 数据与状态
const currentPage = ref(1)
const isLoading = ref(false)
const hasMore = ref(true)
const scrollContainer = ref(null) // 滚动容器引用

// 初始化加载数据并滚动到底部
const initLoad = async () => {
  isLoading.value = true
  try {
    const res = await getMsgListByUID(currentChatter.value.chatterId,currentPage.value++,10);
    currentRecordList.value = res.data.records
    console.log(res.data)
    hasMore.value = (res.data.total - (currentPage.value-1) * 10) > 0
    console.log(hasMore.value)
    // 确保数据渲染后滚动到底部
    await nextTick(() => {
      scrollToBottom()
    })

  } catch (err) {
    console.error('初始化加载失败:', err)
  } finally {
    isLoading.value = false
  }
}

// 加载更多历史数据（向上滚动时触发）
const loadMore = async () => {
  if (isLoading.value || !hasMore.value) return
  isLoading.value = true

  try {
    const res = await getMsgListByUID(currentChatter.value.chatterId,currentPage.value,10);
    if (res.data.records.length === 0) {
      hasMore.value = false
      return
    }
    // if ((res.data.total - currentPage.value * 10) > 0) {
    //   hasMore.value = false
    //   return
    // }

    // 记录当前滚动位置和高度
    const container = scrollContainer.value
    const prevScrollHeight = container.scrollHeight

    // 将新数据插入到列表头部
    currentRecordList.value = [...res.data.records, ...currentRecordList.value]
    currentPage.value += 1

    // 保持滚动位置稳定（避免跳动）
    nextTick(() => {
      container.scrollTop = container.scrollHeight - prevScrollHeight
    })
  } catch (err) {
    console.error('加载更多失败:', err)
  } finally {
    isLoading.value = false
  }
}

// 处理滚动事件
const handleScroll = (e) => {
  const container = e.target
  if (container.scrollTop < 100 && !isLoading.value && hasMore.value) {
    loadMore()
  }
}

// 强制滚动到底部
const scrollToBottom = () => {
  console.log("到底部")
  const container = scrollContainer.value
  console.log(container.scrollTop)
  console.log(container.scrollHeight)
  if (container) {
    container.scrollTop = container.scrollHeight
  }
}

/* 结束 */

/* 下拉获取更多聊天人 */
const disabled = ref(false)// 是否禁用
const load = async () => {

  disabled.value = true
  const res = await getChatterList(++pageParams.page,pageParams.pageSize);
  console.log("开始要数据了：第"+pageParams.page+"页")
  console.log(res)
  if(res.data.records.length === 0){
    disabled.value = true
    return;
  }
  chatterList.value = [...chatterList.value,...res.data.records]
  // 前端去重
  chatterList.value = uniqueList(chatterList.value)
  console.log(chatterList.value)
  disabled.value = false
}

function uniqueList(arr) {
  const newList = []
  arr.forEach((ele)=>{
    let noEle = true
    newList.forEach(item=>{
      if(item.userId === ele.userId){
        noEle = false
      }
    })
    if(noEle){
      newList.push(ele)
    }
  })
  return newList
}


/* 下拉获取更多聊天人结束 */

</script>
<style lang="scss" scoped>
.box-container{
  box-sizing: border-box;
  height: 640px;
  //background-color: white;
}
.el-card{
  --el-card-padding:10px
}
:deep(.el-card__body){
  padding: 0;
}

.el-divider--horizontal{
  margin:5px 0;
}

.container{
  display: flex;
  height: 599px;
  .left{
    width: 240px;
    //background-color: palegreen;
    height: 580px;
    .left-header{
      height: 30px;
      font-size: 13px;
      line-height: 40px;
      text-indent: 20px;
      color:gray;
    }
    .left-content{
      height: 500px;
      overflow: hidden;
      overflow-y: auto;
      .chat-list-box{
        min-height: 0;
        .chat-active{
          background-color: #E4E5E6;
        }
        .chat-item{
          cursor: pointer;
          width: 240px;
          height: 78px;
          //background-color: purple;
          box-sizing: border-box;
          padding: 20px 10px;
          display: flex;
          .chatter-avatar{
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
          }
          .chatter-text-box{

            .chatter-name{
              display: flex;
              justify-content: space-between;
              color: black;
              font-size: 14px;
              width: 155px;
              height: 14px;
              .badge{
                //margin-left: 0px;
                width: 20px;
                height: 20px;
                line-height: 20px;
                text-align: center;
                padding: 0;
                border-radius: 50%;
                color: #fff;
                font-size: 13px;
                background-color: #f16363;
              }
            }
            .chatter-last-record{
              color: gray;
              font-size: 12px;
              width: 155px;
              height: 28px;
              padding: 8px 0;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
        .chat-item:hover{
          background-color: #E4E5E6;
        }
      }
    }
  }
  .right{
    width: 660px;
    //background-color: pink;
    .right-header{
      height: 25px;
      text-align: center;
      line-height: 30px;
      font-size: 14px;
    }
    .right-content{
      overflow-y: scroll;
      height: 400px;
      //background-color: #a5e1ff;
      background-color: #f0fcff;
      position: relative;
      .chat-record-item{
        min-height: 60px;
        .send-time{
          text-align: center;
          height: 20px;
          box-sizing: border-box;
          color: gray;
          font-size: 13px;
          padding: 2px 0;
        }
        .record-info{
          //min-width: 200px;

          //max-width: 500px;
          //background-color: #ff7272;
          display: flex;
          //justify-content: space-between;
          //height: 109px;
          .send-avatar{
            height: 30px;
            width: 30px;
            overflow: hidden;
            border-radius: 50%;
            margin-right: 20px;
          }
          .record-content{
            color: white;
            font-size: 14px;
            min-width: 20px;
            min-height: 40px;
            //background-color: #002dff;
            background-color: #4191ff;
            font-family: 微软雅黑,serif;
            max-width: 400px;
            box-sizing: border-box;
            padding: 10px 15px;
            border-radius: 0 10px 10px 10px;
            .content-img{
              height: 150px;
              img{
                height: 150px;
              }
            }
          }
        }
        .record-info-mine{

          //background-color: #fff3f3;
          display: flex;
          justify-content: flex-end;
          //justify-content: space-between;
          //height: 109px;
          .place-rectify{
            display: flex;
            .send-avatar-mine{
              height: 30px;
              width: 30px;
              overflow: hidden;
              border-radius: 50%;
              margin-left: 20px;
            }
            .record-content-mine{
              color: white;
              font-size: 14px;
              min-width: 20px;
              min-height: 40px;
              background-color: #4191ff;
              font-family: 微软雅黑,serif;
              max-width: 400px;
              box-sizing: border-box;
              padding: 10px 15px;
              border-radius: 10px 0 10px 10px;
              .content-img{
                height: 150px;
                img{
                  height: 150px;
                }
              }
            }
          }

        }
      }

    }
    .send-area{
      position: relative;
      .send-file{
        padding-left: 15px;
        padding-top: 8px ;
        font-size: 25px;
        color: gray;
        .space{
          display: inline-block;
          width: 20px;
        }
      }
      .content-area{
        height: 100px;
        //background-color: #7eff58;

        :deep(.el-input__count){
          //color: red;
          position: absolute;
          top: 80px;
          right:80px
        }
        :deep(.el-textarea__inner){
          border: 0;
        }
      }
      .send{
        position: absolute;
        right: 0;
        bottom: -5px;
      }
    }

  }
}
</style>

<!--经典修改css变量值的方式控制css-->